#!/usr/bin/python3
import numpy
import pandas as pd
import excel_info
from docx import Document
from docx.oxml.ns import qn
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from docx.shared import Pt

from excel_info import ExcelInfo

class Doc:
    path = ""
    name = ""
    target_config = None

    doc = Document()
    def __init__(self, path: str, name: str, target_config):
        self.path = path
        self.name = name
        self.target_config = target_config
        self.init_style()
        pass

    def init_style(self):
        style = self.doc.styles['Normal']
        style.font.name = 'Times New Roman' # 必须先设置font.name
        style.element.rPr.rFonts.set(qn('w:eastAsia'), '宋体')
        pass

    def create_table(self, excel: ExcelInfo):
        e = excel.sheet_info
        sheet_names = e.keys()

        # print(self.target_config)
        cols = len(self.target_config['title'])

        for sheet_name in sheet_names:
            print('正在制作表格: ', sheet_name)
            self.doc.add_paragraph(text=sheet_name + '名单')
            sheet = e[sheet_name]
            table = self.doc.add_table(rows=len(sheet) + 1, cols=cols)
            title_row = table.rows[0].cells

            titles = self.target_config['title']
            # 插入标题行
            for index, title in enumerate(titles):
                title_row[index].text = title
                pass

            for index, obj in enumerate(sheet):
                row = table.rows[index + 1].cells
                for j, title in enumerate(titles):
                    if title == '序号':
                        # print('准备插入序号: ', index + 1)
                        row[j].text = str(index + 1)
                    else:
                        # print('准备插入: ', title, ' 数据: ', obj[title])
                        if obj[title] is not None:
                            if isinstance(obj[title], numpy.float64) is True:
                                row[j].text = str(int(obj[title]))
                            else:
                                row[j].text = str(obj[title])
                    pass
                pass
            self.doc.add_page_break()
            pass
        pass

    def save_doc(self):
        self.doc.save(self.path + self.name)




